<template>
  <div class="address-list">
    <fm-nav-bar :title="navTitle" :border="false">
      <template #left v-if="disableBackArrow">
        <i
          class="fm-icon fm-icon-arrow-left"
          @click="back"
          v-if="navTitle != '通讯录'"
        ></i>
      </template>
    </fm-nav-bar>
    <div class="address-box">
      <fm-search
        v-model="searchValue"
        placeholder="请输入用户名/姓名"
        left-icon=""
        maxlength="50"
        @search="onSearch"
        @clear="onClear"
      >
      </fm-search>
      <!-- 操作记录 -->
      <div
        v-if="!searchInUserPage && depId.length"
        ref="historList"
        class="history-list"
      >
        <div v-for="(item, index) in depId" :key="item.id" class="item">
          <span
            :class="{ last: index === depId.length - 1 }"
            @click="index !== depId.length - 1 ? historyItemClick(item) : ''"
          >
            {{ item.title }}
          </span>
          <i
            v-if="index !== depId.length - 1"
            class="fm-icon fm-icon-arrow"
          ></i>
        </div>
      </div>
      <div
        :style="
          !searchInUserPage && depId.length
            ? `height: calc(100% - ${topHeight2}px );`
            : `height: calc(100% - ${topHeight1}px );`
        "
        class="address-tree"
        :class="{ deptNone: depId.length == 0 }"
      >
        <fm-cell-group v-if="treeShow">
          <fm-cell
            v-for="item in treeList"
            :key="item.id"
            is-link
            :border="false"
            v-debounce="[
              () => {
                handleClick(item)
              },
              500,
              true,
            ]"
          >
            <template #title>
              <div class="img-box">
                <fm-image
                  width="20"
                  height="20"
                  :src="require('@/assets/img/org-tree.png')"
                />
              </div>
              <span class="cell-title">{{ item.content.name }}</span>
            </template>
          </fm-cell>
        </fm-cell-group>
        <div class="user-list" v-else>
          <fm-list
            v-model="loading"
            :finished="finished"
            :immediate-check="false"
            @load="onLoad"
          >
            <div
              v-for="(item, index) in userList"
              :key="item.id"
              class="user"
              @click="viewDetail(item)"
            >
              <img
                v-if="item.avatarToken"
                :src="item.avatarToken | getAvatar"
                class="avatar"
              />
              <div v-else class="avatar avatar-text">
                {{ item.userFullname | getFamilyName }}
              </div>
              <span
                :class="{ last: index === userList.length - 1 }"
                class="name"
              >
                {{ item.userFullname }} ({{ item.userName }})
              </span>
            </div>
            <div class="no-data" v-if="userList.length == 0">
              <img :src="require('@/assets/img/no-user.png')" class="img0" />
              <div class="text0">暂无成员</div>
            </div>
          </fm-list>
        </div>
      </div>
    </div>
    <tabbar></tabbar>
  </div>
</template>
<script>
import { getDept } from './api'
import { searchUser } from '@/api/user'
import { eventBackButton, exitApp } from '@/utils/app'
import { STATUS_BAR_HEIGHT } from '@/store/State/stateTypes'
import tabbar from '@/modules/Tabbar/index'
import { Toast } from 'fawkes-mobile-lib'

export default {
  name: 'addressList',
  components: {
    tabbar,
  },
  filters: {
    getFamilyName(value) {
      return value?.substr(0, 1)
    },
    getAvatar(val) {
      return `${process.env.VUE_APP_BASE_URL}/sys-storage/download_image?f8s=${val}`
    },
  },
  data() {
    return {
      searchValue: '',
      treeData: [], // 存放每一级页面部门列表
      treeList: [], // 当前页面部门列表
      userList: [], // 当前页面用户列表
      disableBackArrow: true, // 返回按钮是否显示,默认不显示
      treeShow: true, // 当前页面是否显示部门
      loading: false,
      finished: false,
      pageNo: 1,
      pageSize: 10,
      navTitle: '通讯录',
      depId: [], //记录访问深度\修改navTitle
      nodeItem: null, //当前部门节点
      searchInUserPage: false, // 是否在用户界面查询
    }
  },
  watch: {
    treeList: {
      handler(newVal) {
        if (newVal && newVal.length != 0) {
          for (let i = 0; i < newVal.length; i++) {
            if (newVal[i].parentId == '0') {
              this.disableBackArrow = false
            } else {
              this.disableBackArrow = true
            }
          }
        }
      },
      deep: true,
    },
    depId(newVal) {
      if (newVal.length > 0) {
        document.removeEventListener('backbutton', eventBackButton, false)
        document.removeEventListener('backbutton', exitApp, false)
        document.removeEventListener('backbutton', this.$back, false)
        document.addEventListener('backbutton', this.back, false)

        if (!this.searchInUserPage) {
          this.$nextTick(() => {
            const w = this.$refs.historList.clientWidth
            const x = this.$refs.historList.scrollWidth

            x > w && this.$refs.historList.scrollTo(x, 0) //操作记录出现滚动条时，默认按最右侧显示
          })
        }
      } else {
        document.addEventListener('backbutton', eventBackButton, false)
        document.removeEventListener('backbutton', this.back, false)
      }
    },
  },
  computed: {
    // 是否在用户列表界面
    inUserPage() {
      // 用部门节点是否为叶子节点判断是在部门还是用户列表页面
      return this.depId.length != 0 && !this.depId.at(-1)?.hasChildren
    },
    statusBarHeight() {
      return this.$store.state[STATUS_BAR_HEIGHT]
    },
    topHeight1() {
      return this.statusBarHeight + 180
    },
    topHeight2() {
      return this.statusBarHeight + 205
    },
  },
  activated() {
    if (this.depId.length > 0) {
      document.addEventListener('backbutton', this.back, false)
      document.removeEventListener('backbutton', this.$back, false)
    } else {
      document.addEventListener('backbutton', eventBackButton, false)
      document.removeEventListener('backbutton', this.$back, false)
    }
  },
  deactivated() {
    if (this.depId.length > 0) {
      document.addEventListener('backbutton', this.$back, false)
      document.removeEventListener('backbutton', this.back, false)
    } else {
      document.removeEventListener('backbutton', eventBackButton, false)
      document.removeEventListener('backbutton', exitApp, false)
      document.addEventListener('backbutton', this.$back, false)
    }
  },
  methods: {
    judgeChild(node, tree) {
      if (tree.length != 0) {
        for (let i = 0; i < tree.length; i++) {
          if (node == tree[i] && tree[i].children) {
            return tree[i].children
          } else if (tree[i].children) {
            this.judgeChild(node, tree[i].children)
          }
        }
      }
    },
    handleClick(item) {
      this.searchValue = ''
      if (this.treeShow) {
        this.nodeItem = item
      }
      // 跳转新部门前记录上一级
      this.depId.push({
        title: item.content.name,
        id: item.id,
        hasChildren: item?.children?.length > 0,
      })
      this.navTitle = item.content.name
      // 部门页面
      if (this.judgeChild(item, this.treeList)) {
        this.treeList = this.judgeChild(item, this.treeList)
        this.treeData.push(this.treeList)
      } else {
        // 人员信息页面
        this.pageNo = 1 //初始化进入时，页码必须为1，否则会被影响
        let data = {
          orgNo: item.content.orgNo,
          searchValue: this.searchValue,
          pageSize: this.pageSize,
          pageNo: this.pageNo,
          accountStatus: 1,
        }
        searchUser(data).then((res) => {
          this.userList = res.data.list
          this.treeShow = false
          this.finished = res.data.isLastPage
        })
      }
    },
    //查看用户详情
    viewDetail(item) {
      const addressHistory = {
        depId: this.depId,
        nodeItem: this.nodeItem,
        treeData: this.treeData,
        treeList: this.treeList,
        userList: this.userList,
        navTitle: this.navTitle,
        treeShow: this.treeShow,
        pageNo: this.pageNo,
        searchValue: this.searchValue,
        searchInUserPage: this.searchInUserPage,
        disableBackArrow: this.disableBackArrow,
      }

      this.$storage.set('addressHistory', JSON.stringify(addressHistory))

      this.$router.push({
        path: '/address/detail',
        query: { userName: item.userName },
      })
    },
    //返回上一级
    back() {
      // this.depId.splice(this.depId.length - 1, 1)
      // 清空搜索框
      this.searchValue = ''
      // 查询页面不要弹出标题，清空操作
      if (this.searchInUserPage || (!this.treeShow && !this.inUserPage)) {
        this.onClear()
        return
      } else {
        // 删除当前标题
        this.depId.pop()
      }

      if (this.depId.length > 0) {
        this.navTitle = this.depId[this.depId.length - 1]?.title
      } else {
        this.navTitle = '通讯录'
        // this.treeData = [this.treeData.shift()]
      }

      if (this.treeShow) {
        this.treeData.pop()
        // 获取上一级部门列表信息
        this.treeList = this.treeData.at(-1)
      } else {
        // 从用户列表页面返回
        this.treeShow = true
      }
    },
    onLoad() {
      this.pageNo += 1
      let data = {
        orgNo: this.nodeItem?.id,
        searchValue: this.searchValue,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        accountStatus: 1,
      }
      searchUser(data).then((res) => {
        this.userList.push(...res.data.list)
        this.treeShow = false
        if (this.userList.length == res.data.total) {
          this.finished = true
        }
      })
      this.loading = false
    },
    onSearch(val) {
      // 空条件等同于清空
      if (val === '' || !val) {
        this.onClear()
      } else {
        Toast.loading({
          message: '加载中...',
          forbidClick: true,
        })

        if (this.inUserPage) {
          this.searchInUserPage = true
        }
        this.pageNo = 1
        let data = {
          searchValue: val,
          pageSize: this.pageSize,
          pageNo: this.pageNo,
          accountStatus: 1,
        }
        searchUser(data)
          .then((res) => {
            this.userList = res.data.list
            this.treeShow = false
          })
          .finally(() => {
            Toast.close()
          })
      }
    },
    onClear() {
      this.searchValue = ''
      // 在用户列表页面清空查询时
      if (this.inUserPage) {
        this.searchInUserPage = false
        this.pageNo = 1
        let data = {
          orgNo: this.nodeItem?.id,
          pageSize: this.pageSize,
          pageNo: this.pageNo,
          accountStatus: 1,
        }
        searchUser(data).then((res) => {
          this.userList = res.data.list
          this.treeShow = false
        })
      } else {
        // 在部门列表页面
        this.userList = []
        this.treeShow = true
      }
    },
    historyItemClick(data) {
      this.searchValue = ''

      let list = []

      this.depId.some((item) => {
        list.push(item)

        if (item.id === data.id) {
          return true
        }
      })

      this.depId = list

      if (this.depId.length) {
        this.navTitle = this.depId.at(-1).title
      } else {
        this.navTitle = '通讯录'
      }

      let tree = []

      this.treeData.some((item) => {
        tree.push(item)

        if (item[0].parentId === this.depId.at(-1).id) {
          return true
        }
      })

      this.treeData = tree
      this.treeList = this.treeData.at(-1)

      !this.treeShow && (this.treeShow = true)
    },
  },
  created() {
    const addressHistory = JSON.parse(this.$storage.get('addressHistory'))

    if (addressHistory) {
      this.depId = addressHistory.depId
      this.nodeItem = addressHistory.nodeItem
      this.treeData = addressHistory.treeData
      this.treeList = addressHistory.treeList
      this.userList = addressHistory.userList
      this.navTitle = addressHistory.navTitle
      this.treeShow = addressHistory.treeShow
      this.pageNo = addressHistory.pageNo
      this.searchValue = addressHistory.searchValue
      this.searchInUserPage = addressHistory.searchInUserPage
      this.disableBackArrow = addressHistory.disableBackArrow

      this.$storage.remove('addressHistory')
    } else {
      getDept({}).then((res) => {
        if (res.status) {
          this.treeList = res.data
          this.treeData.push(res.data)
        }
      })
    }
  },
  mounted() {},
}
</script>
<style scoped lang="less">
.address-list {
  height: 100%;
  background: #eeeeee;

  /deep/ .fm-nav-bar__arrow {
    color: #000 !important;
  }

  .address-box {
    height: 100%;
    background: #ffffff;

    /deep/ .fm-search {
      padding: 0 32px;
    }

    /deep/ .fm-search__content {
      height: 74px;
      border-radius: 16px !important;
    }

    .history-list {
      display: flex;
      align-items: center;
      padding: 32px 0 16px;
      margin: 0 32px;
      overflow-x: auto;
      //隐藏滚动条
      scrollbar-width: none; //firefox
      -ms-overflow-style: none; //IE 10+

      //隐藏滚动条
      &::-webkit-scrollbar {
        display: none; //Chrome | Safari
      }

      .item {
        display: flex;
        align-items: center;
        padding-right: 16px;
        font-size: 30px;
        white-space: nowrap;

        &:last-child {
          padding-right: 0;
        }

        & > {
          span {
            color: #4545d1;
          }

          i {
            margin-left: 8px;
            color: #000000;
          }
        }

        .last {
          color: #818595;
        }
      }
    }

    .address-tree {
      &.deptNone {
        margin-top: 32px;
      }
      background: #f2f3f5;
      overflow-y: auto;
      //隐藏滚动条
      scrollbar-width: none; //firefox
      -ms-overflow-style: none; //IE 10+

      //隐藏滚动条
      &::-webkit-scrollbar {
        display: none; //Chrome | Safari
      }

      /deep/ .fm-hairline--top-bottom::after {
        border-width: 0 !important;
      }

      /deep/ .fm-cell {
        align-items: center;
        height: 144px;
      }

      /deep/ .fm-cell__title {
        display: flex;
        align-items: center;

        .cell-title {
          max-width: 500px;
          font-size: 32px;
          margin-left: 32px;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      /deep/ .fm-cell__right-icon {
        color: #333333;
      }

      .img-box {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 80px;
        height: 80px;
        background-color: rgba(69, 69, 209, 0.08);
        border-radius: 50%;
      }
    }
  }
}

.user {
  display: flex;
  align-items: center;
  height: 144px;
  background: #fff;

  .avatar {
    width: 80px;
    height: 80px;
    margin: 0 32px;
    border-radius: 50%;
  }

  .avatar-text {
    line-height: 80px;
    text-align: center;
    font-size: 32px;
    color: #fff;
    background-color: #4545D1;
  }

  .name {
    position: relative;
    flex: 1;
    height: 144px;
    padding-right: 32px;
    line-height: 144px;
    font-size: 32px;
    color: #15171a;
    overflow: hidden;
    font-family: PingFangSC-Regular, PingFang SC;
    text-overflow: ellipsis;
    white-space: nowrap;

    &::after {
      display: block;
      content: '';
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 2px;
      background-color: #eee;
    }
  }

  .last::after {
    display: none;
  }
}
.no-data {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  flex-direction: column;
  .img0 {
    width: 160px;
    height: 160px;
  }
  .text0 {
    margin-top: 32px;
    font-size: 28px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #414b59;
    line-height: 40px;
  }
}
</style>
